package com.joyd.joydlibexample

import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.Button
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextField
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateListOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.runtime.collectAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.joyd.joydlib.io.WebSocketClient
import kotlinx.coroutines.flow.collect

class WebSocketExampleActivity : ComponentActivity() {
    private lateinit var webSocketClient: WebSocketClient
    private val TAG = "WebSocket示例"
    private val wsUrl = "ws://192.168.2.236:8805"

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        
        // 初始化WebSocketClient
        webSocketClient = WebSocketClient(wsUrl)
        
        // 设置消息回调
        webSocketClient.setOnMessageCallback {
            Log.d(TAG, "Received message: $it")
        }
        
        // 设置状态变化回调
        webSocketClient.setOnStateChangeCallback {
            Log.d(TAG, "Connection state changed: $it")
            // 额外日志，显示详细信息
            when(it) {
                WebSocketClient.ConnectionState.Disconnected -> Log.d(TAG, "连接已断开")
                WebSocketClient.ConnectionState.Connecting -> Log.d(TAG, "正在连接到: $wsUrl")
                WebSocketClient.ConnectionState.Connected -> Log.d(TAG, "连接成功")
                WebSocketClient.ConnectionState.Paused -> Log.d(TAG, "连接已暂停")
            }
        }
        
        // 设置错误回调
        webSocketClient.setOnErrorCallback {
            val errorMsg = it?.message ?: "未知错误"
            Log.e(TAG, "WebSocket error: $errorMsg")
            // 记录完整的异常堆栈
            it?.printStackTrace()
        }
        
        // 配置重连参数
        webSocketClient.setReconnectConfig(
            maxAttempts = 5,
            baseDelayMs = 1000L,
            maxDelayMs = 10000L
        )
        
        // 调用MainActivity中的JoydLibExampleApp Composable函数
        setContent {
            JoydLibExampleApp(
                webSocketClient = webSocketClient,
                wsUrl = wsUrl,
                tag = TAG,
                onDestroy = { webSocketClient.release() }
            )
        }
    }
    
    override fun onDestroy() {
        super.onDestroy()
        webSocketClient.release()
    }
}

// 消息数据类
data class Message(
    val sender: String,
    val content: String,
    val isSystem: Boolean = false
)

@Composable
fun MessageItem(message: Message) {
    Column(modifier = Modifier.padding(4.dp)) {
        Text(
            text = message.sender,
            fontSize = 12.sp,
            color = if (message.isSystem) Color.Gray else Color.Blue
        )
        Text(
            text = message.content,
            fontSize = 14.sp,
            color = if (message.isSystem) Color.Gray else Color.Black
        )
    }
}

@Composable
fun JoydLibExampleApp(
    webSocketClient: WebSocketClient,
    wsUrl: String,
    tag: String,
    onDestroy: () -> Unit
) {
    val context = LocalContext.current
    // 使用collectAsState()观察connectionState的变化
    val connectionState by webSocketClient.connectionState.collectAsState()
    // 根据实际连接状态初始化isConnected
    var isConnected by remember(connectionState) { mutableStateOf(connectionState == WebSocketClient.ConnectionState.Connected) }
    var inputMessage by remember { mutableStateOf("") }
    val messageHistory = remember { mutableStateListOf<Message>() }
    
    // 监听连接状态变化
    LaunchedEffect(Unit) {
        webSocketClient.connectionState.collect {
            isConnected = it == WebSocketClient.ConnectionState.Connected
            // 将连接状态转换为友好的文本描述
            val statusText = when(it) {
                WebSocketClient.ConnectionState.Disconnected -> "已断开"
                WebSocketClient.ConnectionState.Connecting -> "连接中..."
                WebSocketClient.ConnectionState.Connected -> "已连接"
                WebSocketClient.ConnectionState.Paused -> "已暂停"
                else -> "未知"
            }
            messageHistory.add(Message("系统", "连接状态: $statusText", isSystem = true))
        }
    }
    
    // 设置消息接收和错误回调
    LaunchedEffect(Unit) {
        webSocketClient.setOnMessageCallback {
            messageHistory.add(Message("服务器", it))
        }
        
        // 在Composable函数中设置错误回调，以便访问messageHistory
        webSocketClient.setOnErrorCallback {
            val errorMsg = it?.message ?: "未知错误"
            Log.e(tag, "WebSocket error: $errorMsg")
            it?.printStackTrace()
            messageHistory.add(Message("系统", "连接错误: $errorMsg", isSystem = true))
        }
    }
    
    MaterialTheme {
        Surface(modifier = Modifier.fillMaxSize()) {
            Column(
                modifier = Modifier.fillMaxSize().padding(16.dp)
            ) {
                // 标题和连接状态
                Column(modifier = Modifier.fillMaxWidth(), horizontalAlignment = Alignment.CenterHorizontally) {
                    Text(text = "WebSocket客户端示例", fontSize = 24.sp)
                    // 显示用户友好的连接状态文本
                    Text(
                        text = when(connectionState) {
                            WebSocketClient.ConnectionState.Disconnected -> "连接状态: 已断开"
                            WebSocketClient.ConnectionState.Connecting -> "连接状态: 连接中..."
                            WebSocketClient.ConnectionState.Connected -> "连接状态: 已连接"
                            WebSocketClient.ConnectionState.Paused -> "连接状态: 已暂停"
                            else -> "连接状态: 未知"
                        }, 
                        color = when(connectionState) {
                            WebSocketClient.ConnectionState.Connected -> Color.Green
                            WebSocketClient.ConnectionState.Connecting -> Color.Yellow
                            WebSocketClient.ConnectionState.Paused -> Color.Blue
                            else -> Color.Red
                        },
                        fontSize = 16.sp,
                        modifier = Modifier.padding(8.dp)
                    )
                    // 显示实际连接的服务器地址
                    Text(text = "服务器地址: $wsUrl", fontSize = 14.sp)
                }
                
                // 连接控制按钮
                Row(
                    modifier = Modifier.fillMaxWidth().padding(8.dp),
                    horizontalArrangement = Arrangement.SpaceEvenly,
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Button(
                        onClick = { webSocketClient.connect() },
                        enabled = !isConnected
                    ) {
                        Text("连接")
                    }
                    
                    Button(
                        onClick = { webSocketClient.disconnect() },
                        enabled = isConnected
                    ) {
                        Text("断开")
                    }
                    
                    Button(
                        onClick = { webSocketClient.pause() },
                        enabled = isConnected
                    ) {
                        Text("暂停")
                    }
                    
                    Button(
                        onClick = { webSocketClient.resume() },
                        enabled = connectionState == WebSocketClient.ConnectionState.Paused
                    ) {
                        Text("恢复")
                    }
                }
                
                // 消息历史
                LazyColumn(
                    modifier = Modifier.weight(1f).fillMaxWidth().padding(8.dp)
                ) {
                    items(messageHistory) {
                        MessageItem(it)
                    }
                }
                
                // 消息输入和发送
                Row(
                    modifier = Modifier.fillMaxWidth().padding(8.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    TextField(
                        value = inputMessage,
                        onValueChange = { inputMessage = it },
                        modifier = Modifier.weight(1f),
                        placeholder = { Text("输入消息...") },
                        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Text)
                    )
                    
                    Button(
                        onClick = {
                            if (isConnected && inputMessage.isNotEmpty()) {
                                val success = webSocketClient.send(inputMessage)
                                if (success) {
                                    messageHistory.add(Message("我", inputMessage))
                                    inputMessage = ""
                                } else {
                                    messageHistory.add(Message("系统", "发送失败", isSystem = true))
                                }
                            }
                        },
                        enabled = isConnected && inputMessage.isNotEmpty()
                    ) {
                        Text("发送")
                    }
                }
            }
        }
    }
}

@Preview(showBackground = true)
@Composable
fun JoydLibExamplePreview() {
    // 预览时使用空实现，统一使用相同的URL和配置
    val wsUrl = "ws://localhost:8805"
    val mockWebSocketClient = WebSocketClient(wsUrl)
    val previewTag = "WebSocket预览"
    
    // 与实际代码保持一致的重连配置
    mockWebSocketClient.setReconnectConfig(
        maxAttempts = 5,
        baseDelayMs = 1000L,
        maxDelayMs = 10000L
    )
    
    JoydLibExampleApp(mockWebSocketClient, wsUrl, previewTag) {}
}